/**
 * 库存控制器
 * 提供库存相关功能的处理方法
 */
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

/**
 * 获取库存概览
 * 返回所有商品的库存状态
 */
exports.getInventoryOverview = async (req, res) => {
  try {
    // 查询所有有效商品及其库存信息
    const products = await prisma.product.findMany({
      where: { status: true },
      include: {
        category: {
          select: { id: true, name: true }
        },
        inventoryRecords: {
          include: {
            warehouse: {
              select: { id: true, name: true }
            }
          }
        }
      }
    });
    
    // 统计预警和缺货商品数量
    let warningProducts = 0;
    let outOfStockProducts = 0;
    
    products.forEach(product => {
      if (product.stockStatus === 'warning') {
        warningProducts++;
      } else if (product.stockStatus === 'out_of_stock') {
        outOfStockProducts++;
      }
    });
    
    return res.status(200).json({
      success: true,
      data: {
        products,
        totalProducts: products.length,
        warningProducts,
        outOfStockProducts
      }
    });
  } catch (error) {
    console.error('获取库存概览失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取库存概览失败',
      error: error.message
    });
  }
};

/**
 * 调整库存
 * 增加或减少指定商品在指定仓库的库存
 */
exports.adjustInventory = async (req, res) => {
  try {
    const { productId, warehouseId, adjustmentQuantity, adjustmentType, remarks } = req.body;
    const userId = req.user?.id || 1; // 默认用户ID为1，用于测试
    
    // 参数验证
    if (!productId || !warehouseId || adjustmentQuantity === undefined || !adjustmentType) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数'
      });
    }
    
    // 查询商品信息
    const product = await prisma.product.findUnique({
      where: { id: parseInt(productId) }
    });
    
    if (!product) {
      return res.status(404).json({
        success: false,
        message: '商品不存在'
      });
    }
    
    // 查询仓库信息
    const warehouse = await prisma.warehouse.findUnique({
      where: { id: parseInt(warehouseId) }
    });
    
    if (!warehouse) {
      return res.status(404).json({
        success: false,
        message: '仓库不存在'
      });
    }
    
    // 查询当前库存记录
    let inventoryRecord = await prisma.inventoryRecord.findFirst({
      where: {
        productId: parseInt(productId),
        warehouseId: parseInt(warehouseId)
      }
    });
    
    const beforeQuantity = inventoryRecord ? inventoryRecord.quantity : 0;
    let afterQuantity = beforeQuantity;
    
    // 根据调整类型计算新库存
    if (adjustmentType === 1) { // 增加
      afterQuantity += parseInt(adjustmentQuantity);
    } else if (adjustmentType === 2) { // 减少
      afterQuantity -= parseInt(adjustmentQuantity);
      if (afterQuantity < 0) {
        return res.status(400).json({
          success: false,
          message: '库存不足，无法调整'
        });
      }
    } else if (adjustmentType === 3) { // 设置为指定值
      afterQuantity = parseInt(adjustmentQuantity);
      if (afterQuantity < 0) {
        return res.status(400).json({
          success: false,
          message: '库存不能为负数'
        });
      }
    } else {
      return res.status(400).json({
        success: false,
        message: '无效的调整类型'
      });
    }
    
    // 更新库存记录
    if (inventoryRecord) {
      // 更新已有记录
      inventoryRecord = await prisma.inventoryRecord.update({
        where: { id: inventoryRecord.id },
        data: { quantity: afterQuantity }
      });
    } else {
      // 创建新记录
      inventoryRecord = await prisma.inventoryRecord.create({
        data: {
          productId: parseInt(productId),
          warehouseId: parseInt(warehouseId),
          quantity: afterQuantity
        }
      });
    }
    
    // 更新商品总库存
    const totalInventory = await prisma.inventoryRecord.findMany({
      where: { productId: parseInt(productId) }
    });
    
    const newTotalQuantity = totalInventory.reduce((sum, record) => sum + record.quantity, 0);
    
    await prisma.product.update({
      where: { id: parseInt(productId) },
      data: {
        stockQuantity: newTotalQuantity,
        stockStatus: newTotalQuantity <= 0 ? 'out_of_stock' : (newTotalQuantity <= product.minimumStock ? 'warning' : 'normal')
      }
    });
    
    // 创建调整记录
    const adjustment = await prisma.stockAdjustment.create({
      data: {
        productId: parseInt(productId),
        warehouseId: parseInt(warehouseId),
        adjustmentQuantity: parseInt(adjustmentQuantity),
        beforeQuantity,
        afterQuantity,
        adjustmentType: parseInt(adjustmentType),
        operatorId: userId,
        adjustmentDate: new Date(),
        remarks: remarks || ''
      }
    });
    
    return res.status(200).json({
      success: true,
      data: {
        adjustment,
        inventory: inventoryRecord
      },
      message: '库存调整成功'
    });
  } catch (error) {
    console.error('库存调整失败:', error);
    return res.status(500).json({
      success: false,
      message: '库存调整失败',
      error: error.message
    });
  }
};

/**
 * 获取库存状态报表
 * 返回各商品的库存状态数据
 */
exports.getInventoryStatusReport = async (req, res) => {
  try {
    const { categoryId, warehouseId } = req.query;
    
    // 构建查询条件
    const where = { status: true };
    
    if (categoryId) {
      where.categoryId = parseInt(categoryId);
    }
    
    // 查询商品库存信息
    const products = await prisma.product.findMany({
      where,
      include: {
        category: {
          select: { id: true, name: true }
        },
        inventoryRecords: {
          include: {
            warehouse: {
              select: { id: true, name: true }
            }
          }
        }
      }
    });
    
    // 根据仓库筛选数据
    let reportData = products.map(product => {
      const records = warehouseId
        ? product.inventoryRecords.filter(record => record.warehouseId === parseInt(warehouseId))
        : product.inventoryRecords;
      
      const warehouseQuantity = warehouseId
        ? records.reduce((sum, record) => sum + record.quantity, 0)
        : null;
      
      return {
        id: product.id,
        name: product.name,
        categoryName: product.category?.name || '未分类',
        stockQuantity: product.stockQuantity,
        stockUnit: product.stockUnit,
        minimumStock: product.minimumStock,
        maximumStock: product.maximumStock,
        stockStatus: product.stockStatus,
        warehouseQuantity,
        warehouseRecords: records.map(record => ({
          warehouseId: record.warehouseId,
          warehouseName: record.warehouse.name,
          quantity: record.quantity
        }))
      };
    });
    
    return res.status(200).json({
      success: true,
      data: reportData
    });
  } catch (error) {
    console.error('获取库存状态报表失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取库存状态报表失败',
      error: error.message
    });
  }
};

/**
 * 获取库存流水报表
 * 返回库存变动记录
 */
exports.getInventoryMovementReport = async (req, res) => {
  try {
    const { startDate, endDate, productId, warehouseId, movementType } = req.query;
    
    // 构建查询条件
    const where = {};
    
    if (startDate && endDate) {
      where.createdAt = {
        gte: new Date(startDate),
        lte: new Date(endDate)
      };
    }
    
    if (productId) {
      where.productId = parseInt(productId);
    }
    
    if (warehouseId) {
      where.warehouseId = parseInt(warehouseId);
    }
    
    if (movementType) {
      where.movementType = parseInt(movementType);
    }
    
    // 查询库存变动记录
    const movements = await prisma.stockMovement.findMany({
      where,
      include: {
        product: {
          select: {
            id: true,
            name: true,
            stockUnit: true
          }
        },
        warehouse: {
          select: {
            id: true,
            name: true
          }
        },
        operator: {
          select: {
            id: true,
            name: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    });
    
    return res.status(200).json({
      success: true,
      data: movements
    });
  } catch (error) {
    console.error('获取库存流水报表失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取库存流水报表失败',
      error: error.message
    });
  }
};

/**
 * 获取库存价值报表
 * 返回库存商品价值统计
 */
exports.getInventoryValueReport = async (req, res) => {
  try {
    const { categoryId, warehouseId } = req.query;
    
    // 构建查询条件
    const where = { status: true };
    
    if (categoryId) {
      where.categoryId = parseInt(categoryId);
    }
    
    // 查询商品库存信息
    const products = await prisma.product.findMany({
      where,
      include: {
        category: {
          select: { id: true, name: true }
        },
        inventoryRecords: {
          include: {
            warehouse: {
              select: { id: true, name: true }
            }
          }
        }
      }
    });
    
    // 计算库存价值
    let totalValue = 0;
    let categoryValues = {};
    
    const reportData = products.map(product => {
      const records = warehouseId
        ? product.inventoryRecords.filter(record => record.warehouseId === parseInt(warehouseId))
        : product.inventoryRecords;
      
      const quantity = warehouseId
        ? records.reduce((sum, record) => sum + record.quantity, 0)
        : product.stockQuantity;
      
      const value = quantity * (product.costPrice || 0);
      
      // 累计总价值
      totalValue += value;
      
      // 按分类累计
      const categoryName = product.category?.name || '未分类';
      if (!categoryValues[categoryName]) {
        categoryValues[categoryName] = 0;
      }
      categoryValues[categoryName] += value;
      
      return {
        id: product.id,
        name: product.name,
        categoryName,
        stockQuantity: quantity,
        stockUnit: product.stockUnit,
        costPrice: product.costPrice,
        value
      };
    });
    
    // 转换分类统计为数组
    const categoryData = Object.keys(categoryValues).map(name => ({
      categoryName: name,
      value: categoryValues[name]
    }));
    
    return res.status(200).json({
      success: true,
      data: {
        products: reportData,
        totalValue,
        categoryData
      }
    });
  } catch (error) {
    console.error('获取库存价值报表失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取库存价值报表失败',
      error: error.message
    });
  }
};

/**
 * 获取库存周转率报表
 * 返回商品库存周转情况
 */
exports.getInventoryTurnoverReport = async (req, res) => {
  try {
    const { startDate, endDate, categoryId } = req.query;
    
    // 参数验证
    if (!startDate || !endDate) {
      return res.status(400).json({
        success: false,
        message: '开始日期和结束日期是必须的'
      });
    }
    
    // 构建查询条件
    const productWhere = { status: true };
    
    if (categoryId) {
      productWhere.categoryId = parseInt(categoryId);
    }
    
    // 查询商品
    const products = await prisma.product.findMany({
      where: productWhere,
      include: {
        category: {
          select: { id: true, name: true }
        }
      }
    });
    
    // 查询指定时间段内的出库记录
    const startDateObj = new Date(startDate);
    const endDateObj = new Date(endDate);
    
    const stockOutItems = await prisma.stockOutItem.findMany({
      where: {
        stockOutOrder: {
          orderDate: {
            gte: startDateObj,
            lte: endDateObj
          },
          status: 'completed'
        }
      },
      include: {
        stockOutOrder: {
          select: {
            id: true,
            orderDate: true
          }
        }
      }
    });
    
    // 计算每个商品的周转情况
    const reportData = await Promise.all(products.map(async (product) => {
      // 商品的出库数量
      const outItems = stockOutItems.filter(item => item.productId === product.id);
      const outQuantity = outItems.reduce((sum, item) => sum + item.quantity, 0);
      
      // 获取期初库存
      const startInventory = await getProductInventoryAt(product.id, startDateObj);
      
      // 获取期末库存
      const endInventory = await getProductInventoryAt(product.id, endDateObj);
      
      // 计算平均库存
      const avgInventory = (startInventory + endInventory) / 2;
      
      // 计算周转率
      const turnoverRate = avgInventory > 0 ? outQuantity / avgInventory : 0;
      
      // 计算周转天数 (使用时间段总天数)
      const days = Math.round((endDateObj - startDateObj) / (1000 * 60 * 60 * 24));
      const turnoverDays = turnoverRate > 0 ? days / turnoverRate : 0;
      
      return {
        id: product.id,
        name: product.name,
        categoryName: product.category?.name || '未分类',
        startInventory,
        endInventory,
        avgInventory,
        outQuantity,
        turnoverRate: parseFloat(turnoverRate.toFixed(2)),
        turnoverDays: Math.round(turnoverDays)
      };
    }));
    
    return res.status(200).json({
      success: true,
      data: reportData
    });
  } catch (error) {
    console.error('获取库存周转率报表失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取库存周转率报表失败',
      error: error.message
    });
  }
};

/**
 * 导出库存报表
 * 导出指定类型的库存报表为Excel
 */
exports.exportInventoryReport = async (req, res) => {
  try {
    const { type } = req.params;
    const { startDate, endDate, categoryId, warehouseId } = req.query;
    
    let reportData = [];
    let filename = '';
    
    // 根据报表类型获取数据
    switch (type) {
      case 'status':
        // 重用状态报表逻辑
        reportData = await getInventoryStatusData(categoryId, warehouseId);
        filename = '库存状态报表';
        break;
        
      case 'movement':
        // 重用流水报表逻辑
        reportData = await getInventoryMovementData(startDate, endDate, categoryId, warehouseId);
        filename = '库存流水报表';
        break;
        
      case 'value':
        // 重用价值报表逻辑
        reportData = await getInventoryValueData(categoryId, warehouseId);
        filename = '库存价值报表';
        break;
        
      case 'turnover':
        // 重用周转率报表逻辑
        reportData = await getInventoryTurnoverData(startDate, endDate, categoryId);
        filename = '库存周转率报表';
        break;
        
      default:
        return res.status(400).json({
          success: false,
          message: '无效的报表类型'
        });
    }
    
    // 创建Excel文件
    const excelBuffer = await createExcelReport(reportData, type);
    
    // 设置响应头
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename=${encodeURIComponent(filename)}.xlsx`);
    
    // 发送Excel文件
    return res.send(excelBuffer);
  } catch (error) {
    console.error('导出库存报表失败:', error);
    return res.status(500).json({
      success: false,
      message: '导出库存报表失败',
      error: error.message
    });
  }
};

/**
 * 辅助函数：获取商品在指定时间点的库存
 */
async function getProductInventoryAt(productId, date) {
  try {
    // 查询该日期之前的最后一条库存记录
    const record = await prisma.inventoryRecord.findFirst({
      where: {
        productId,
        createdAt: {
          lte: date
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    });
    
    return record ? record.quantity : 0;
  } catch (error) {
    console.error('获取历史库存失败:', error);
    return 0;
  }
}

/**
 * 辅助函数：获取库存状态报表数据
 */
async function getInventoryStatusData(categoryId, warehouseId) {
  // 构建查询条件
  const where = { status: true };
  
  if (categoryId) {
    where.categoryId = parseInt(categoryId);
  }
  
  // 查询商品库存信息
  const products = await prisma.product.findMany({
    where,
    include: {
      category: {
        select: { id: true, name: true }
      },
      inventoryRecords: {
        include: {
          warehouse: {
            select: { id: true, name: true }
          }
        }
      }
    }
  });
  
  // 根据仓库筛选数据
  return products.map(product => {
    const records = warehouseId
      ? product.inventoryRecords.filter(record => record.warehouseId === parseInt(warehouseId))
      : product.inventoryRecords;
    
    const warehouseQuantity = warehouseId
      ? records.reduce((sum, record) => sum + record.quantity, 0)
      : null;
    
    return {
      id: product.id,
      name: product.name,
      categoryName: product.category?.name || '未分类',
      stockQuantity: product.stockQuantity,
      stockUnit: product.stockUnit,
      minimumStock: product.minimumStock,
      maximumStock: product.maximumStock,
      stockStatus: product.stockStatus,
      warehouseQuantity,
      warehouseRecords: records.map(record => ({
        warehouseId: record.warehouseId,
        warehouseName: record.warehouse.name,
        quantity: record.quantity
      }))
    };
  });
}

/**
 * 辅助函数：获取库存流水报表数据
 */
async function getInventoryMovementData(startDate, endDate, productId, warehouseId) {
  // 构建查询条件
  const where = {};
  
  if (startDate && endDate) {
    where.createdAt = {
      gte: new Date(startDate),
      lte: new Date(endDate)
    };
  }
  
  if (productId) {
    where.productId = parseInt(productId);
  }
  
  if (warehouseId) {
    where.warehouseId = parseInt(warehouseId);
  }
  
  // 查询库存变动记录
  return await prisma.stockMovement.findMany({
    where,
    include: {
      product: {
        select: {
          id: true,
          name: true,
          stockUnit: true
        }
      },
      warehouse: {
        select: {
          id: true,
          name: true
        }
      },
      operator: {
        select: {
          id: true,
          name: true
        }
      }
    },
    orderBy: {
      createdAt: 'desc'
    }
  });
}

/**
 * 辅助函数：获取库存价值报表数据
 */
async function getInventoryValueData(categoryId, warehouseId) {
  // 构建查询条件
  const where = { status: true };
  
  if (categoryId) {
    where.categoryId = parseInt(categoryId);
  }
  
  // 查询商品库存信息
  const products = await prisma.product.findMany({
    where,
    include: {
      category: {
        select: { id: true, name: true }
      },
      inventoryRecords: {
        include: {
          warehouse: {
            select: { id: true, name: true }
          }
        }
      }
    }
  });
  
  // 计算库存价值
  let totalValue = 0;
  let categoryValues = {};
  
  const reportData = products.map(product => {
    const records = warehouseId
      ? product.inventoryRecords.filter(record => record.warehouseId === parseInt(warehouseId))
      : product.inventoryRecords;
    
    const quantity = warehouseId
      ? records.reduce((sum, record) => sum + record.quantity, 0)
      : product.stockQuantity;
    
    const value = quantity * (product.costPrice || 0);
    
    // 累计总价值
    totalValue += value;
    
    // 按分类累计
    const categoryName = product.category?.name || '未分类';
    if (!categoryValues[categoryName]) {
      categoryValues[categoryName] = 0;
    }
    categoryValues[categoryName] += value;
    
    return {
      id: product.id,
      name: product.name,
      categoryName,
      stockQuantity: quantity,
      stockUnit: product.stockUnit,
      costPrice: product.costPrice,
      value
    };
  });
  
  // 转换分类统计为数组
  const categoryData = Object.keys(categoryValues).map(name => ({
    categoryName: name,
    value: categoryValues[name]
  }));
  
  return {
    products: reportData,
    totalValue,
    categoryData
  };
}

/**
 * 辅助函数：获取库存周转率报表数据
 */
async function getInventoryTurnoverData(startDate, endDate, categoryId) {
  if (!startDate || !endDate) {
    return [];
  }
  
  // 构建查询条件
  const productWhere = { status: true };
  
  if (categoryId) {
    productWhere.categoryId = parseInt(categoryId);
  }
  
  // 查询商品
  const products = await prisma.product.findMany({
    where: productWhere,
    include: {
      category: {
        select: { id: true, name: true }
      }
    }
  });
  
  // 查询指定时间段内的出库记录
  const startDateObj = new Date(startDate);
  const endDateObj = new Date(endDate);
  
  const stockOutItems = await prisma.stockOutItem.findMany({
    where: {
      stockOutOrder: {
        orderDate: {
          gte: startDateObj,
          lte: endDateObj
        },
        status: 'completed'
      }
    },
    include: {
      stockOutOrder: {
        select: {
          id: true,
          orderDate: true
        }
      }
    }
  });
  
  // 计算每个商品的周转情况
  return await Promise.all(products.map(async (product) => {
    // 商品的出库数量
    const outItems = stockOutItems.filter(item => item.productId === product.id);
    const outQuantity = outItems.reduce((sum, item) => sum + item.quantity, 0);
    
    // 获取期初库存
    const startInventory = await getProductInventoryAt(product.id, startDateObj);
    
    // 获取期末库存
    const endInventory = await getProductInventoryAt(product.id, endDateObj);
    
    // 计算平均库存
    const avgInventory = (startInventory + endInventory) / 2;
    
    // 计算周转率
    const turnoverRate = avgInventory > 0 ? outQuantity / avgInventory : 0;
    
    // 计算周转天数 (使用时间段总天数)
    const days = Math.round((endDateObj - startDateObj) / (1000 * 60 * 60 * 24));
    const turnoverDays = turnoverRate > 0 ? days / turnoverRate : 0;
    
    return {
      id: product.id,
      name: product.name,
      categoryName: product.category?.name || '未分类',
      startInventory,
      endInventory,
      avgInventory,
      outQuantity,
      turnoverRate: parseFloat(turnoverRate.toFixed(2)),
      turnoverDays: Math.round(turnoverDays)
    };
  }));
}

/**
 * 辅助函数：创建Excel报表
 */
async function createExcelReport(data, type) {
  // 这里需要实现根据不同报表类型创建Excel的逻辑
  // 由于我们在测试阶段，简单返回一个空buffer
  return Buffer.from('测试报表');
}

/**
 * 获取所有仓库
 */
exports.getAllWarehouses = async (req, res) => {
  try {
    const warehouses = await prisma.warehouse.findMany();
    
    return res.status(200).json({
      success: true,
      data: warehouses
    });
  } catch (error) {
    console.error('获取仓库列表失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取仓库列表失败',
      error: error.message
    });
  }
};

/**
 * 获取仓库详情
 */
exports.getWarehouseById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const warehouse = await prisma.warehouse.findUnique({
      where: { id: parseInt(id) }
    });
    
    if (!warehouse) {
      return res.status(404).json({
        success: false,
        message: '仓库不存在'
      });
    }
    
    return res.status(200).json({
      success: true,
      data: warehouse
    });
  } catch (error) {
    console.error('获取仓库详情失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取仓库详情失败',
      error: error.message
    });
  }
};

/**
 * 创建仓库
 */
exports.createWarehouse = async (req, res) => {
  try {
    const { name, location, managerId, contact, status, remarks } = req.body;
    
    // 验证必要字段
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '仓库名称不能为空'
      });
    }
    
    // 检查同名仓库是否已存在
    const existingWarehouse = await prisma.warehouse.findFirst({
      where: { name }
    });
    
    if (existingWarehouse) {
      return res.status(400).json({
        success: false,
        message: '同名仓库已存在'
      });
    }
    
    // 将status转换为布尔值
    const statusValue = status === true || status === 1 || status === '1';
    
    // 创建仓库
    const warehouse = await prisma.warehouse.create({
      data: {
        name,
        location,
        managerId: managerId ? parseInt(managerId) : null,
        contact,
        status: statusValue,
        remarks
      }
    });
    
    return res.status(201).json({
      success: true,
      data: warehouse,
      message: '仓库创建成功'
    });
  } catch (error) {
    console.error('创建仓库失败:', error);
    return res.status(500).json({
      success: false,
      message: '创建仓库失败',
      error: error.message
    });
  }
};

/**
 * 更新仓库
 */
exports.updateWarehouse = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, location, managerId, contact, status, remarks } = req.body;
    
    // 验证必要字段
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '仓库名称不能为空'
      });
    }
    
    // 检查仓库是否存在
    const existingWarehouse = await prisma.warehouse.findUnique({
      where: { id: parseInt(id) }
    });
    
    if (!existingWarehouse) {
      return res.status(404).json({
        success: false,
        message: '仓库不存在'
      });
    }
    
    // 检查同名仓库是否已存在
    const sameNameWarehouse = await prisma.warehouse.findFirst({
      where: {
        name,
        id: { not: parseInt(id) }
      }
    });
    
    if (sameNameWarehouse) {
      return res.status(400).json({
        success: false,
        message: '同名仓库已存在'
      });
    }
    
    // 将status转换为布尔值
    let statusValue = existingWarehouse.status;
    if (status !== undefined) {
      statusValue = status === true || status === 1 || status === '1';
    }
    
    // 更新仓库
    const warehouse = await prisma.warehouse.update({
      where: { id: parseInt(id) },
      data: {
        name,
        location,
        managerId: managerId ? parseInt(managerId) : null,
        contact,
        status: statusValue,
        remarks
      }
    });
    
    return res.status(200).json({
      success: true,
      data: warehouse,
      message: '仓库更新成功'
    });
  } catch (error) {
    console.error('更新仓库失败:', error);
    return res.status(500).json({
      success: false,
      message: '更新仓库失败',
      error: error.message
    });
  }
};

/**
 * 删除仓库
 */
exports.deleteWarehouse = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查仓库是否存在
    const warehouse = await prisma.warehouse.findUnique({
      where: { id: parseInt(id) }
    });
    
    if (!warehouse) {
      return res.status(404).json({
        success: false,
        message: '仓库不存在'
      });
    }
    
    // 检查仓库是否有关联的库存记录
    const inventoryRecords = await prisma.inventoryRecord.count({
      where: { warehouseId: parseInt(id) }
    });
    
    if (inventoryRecords > 0) {
      return res.status(400).json({
        success: false,
        message: '仓库已有库存记录，无法删除'
      });
    }
    
    // 删除仓库
    await prisma.warehouse.delete({
      where: { id: parseInt(id) }
    });
    
    return res.status(200).json({
      success: true,
      message: '仓库删除成功'
    });
  } catch (error) {
    console.error('删除仓库失败:', error);
    return res.status(500).json({
      success: false,
      message: '删除仓库失败',
      error: error.message
    });
  }
};

/**
 * 获取所有供应商
 */
exports.getAllSuppliers = async (req, res) => {
  try {
    // 获取所有供应商，包括停用的
    const suppliers = await prisma.supplier.findMany({
      orderBy: {
        name: 'asc'
      }
    });
    
    console.log('返回的供应商数据:', suppliers);
    
    return res.status(200).json({
      success: true,
      data: suppliers
    });
  } catch (error) {
    console.error('获取供应商列表失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取供应商列表失败',
      error: error.message
    });
  }
};

/**
 * 获取供应商详情
 */
exports.getSupplierById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const supplier = await prisma.supplier.findUnique({
      where: { id: parseInt(id) }
    });
    
    if (!supplier) {
      return res.status(404).json({
        success: false,
        message: '供应商不存在'
      });
    }
    
    return res.status(200).json({
      success: true,
      data: supplier
    });
  } catch (error) {
    console.error('获取供应商详情失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取供应商详情失败',
      error: error.message
    });
  }
};

/**
 * 创建供应商
 */
exports.createSupplier = async (req, res) => {
  try {
    const { name, contactPerson, phone, email, address, remarks } = req.body;
    
    // 验证必要字段
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '供应商名称不能为空'
      });
    }
    
    // 检查同名供应商是否已存在
    const existingSupplier = await prisma.supplier.findFirst({
      where: { name }
    });
    
    if (existingSupplier) {
      return res.status(400).json({
        success: false,
        message: '同名供应商已存在'
      });
    }
    
    // 创建供应商
    const supplier = await prisma.supplier.create({
      data: {
        name,
        contactPerson,
        phone,
        email,
        address,
        status: true,
        remarks
      }
    });
    
    return res.status(201).json({
      success: true,
      data: supplier,
      message: '供应商创建成功'
    });
  } catch (error) {
    console.error('创建供应商失败:', error);
    return res.status(500).json({
      success: false,
      message: '创建供应商失败',
      error: error.message
    });
  }
};

/**
 * 更新供应商
 */
exports.updateSupplier = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, contactPerson, phone, email, address, status, remarks } = req.body;
    
    // 验证必要字段
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '供应商名称不能为空'
      });
    }
    
    // 检查供应商是否存在
    const existingSupplier = await prisma.supplier.findUnique({
      where: { id: parseInt(id) }
    });
    
    if (!existingSupplier) {
      return res.status(404).json({
        success: false,
        message: '供应商不存在'
      });
    }
    
    // 检查同名供应商是否已存在
    const sameNameSupplier = await prisma.supplier.findFirst({
      where: {
        name,
        id: { not: parseInt(id) }
      }
    });
    
    if (sameNameSupplier) {
      return res.status(400).json({
        success: false,
        message: '同名供应商已存在'
      });
    }
    
    // 更新供应商
    const supplier = await prisma.supplier.update({
      where: { id: parseInt(id) },
      data: {
        name,
        contactPerson,
        phone,
        email,
        address,
        status: status !== undefined ? status : existingSupplier.status,
        remarks
      }
    });
    
    return res.status(200).json({
      success: true,
      data: supplier,
      message: '供应商更新成功'
    });
  } catch (error) {
    console.error('更新供应商失败:', error);
    return res.status(500).json({
      success: false,
      message: '更新供应商失败',
      error: error.message
    });
  }
};

/**
 * 删除供应商
 */
exports.deleteSupplier = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查供应商是否存在
    const supplier = await prisma.supplier.findUnique({
      where: { id: parseInt(id) }
    });
    
    if (!supplier) {
      return res.status(404).json({
        success: false,
        message: '供应商不存在'
      });
    }
    
    // 检查供应商是否有关联的入库单
    const stockInOrders = await prisma.stockInOrder.count({
      where: { supplierId: parseInt(id) }
    });
    
    if (stockInOrders > 0) {
      return res.status(400).json({
        success: false,
        message: '供应商已有入库单记录，无法删除'
      });
    }
    
    // 删除供应商
    await prisma.supplier.delete({
      where: { id: parseInt(id) }
    });
    
    return res.status(200).json({
      success: true,
      message: '供应商删除成功'
    });
  } catch (error) {
    console.error('删除供应商失败:', error);
    return res.status(500).json({
      success: false,
      message: '删除供应商失败',
      error: error.message
    });
  }
};

/**
 * 获取商品库存详情
 */
exports.getProductInventory = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查询商品信息
    const product = await prisma.product.findUnique({
      where: { id: parseInt(id) },
      include: {
        category: true,
        inventoryRecords: {
          include: {
            warehouse: true
          }
        }
      }
    });
    
    if (!product) {
      return res.status(404).json({
        success: false,
        message: '商品不存在'
      });
    }
    
    // 查询库存调整记录
    const adjustments = await prisma.stockAdjustment.findMany({
      where: { productId: parseInt(id) },
      orderBy: { adjustmentDate: 'desc' },
      take: 10,
      include: {
        warehouse: true,
        operator: {
          select: { id: true, name: true }
        }
      }
    });
    
    return res.status(200).json({
      success: true,
      data: {
        product,
        adjustments
      }
    });
  } catch (error) {
    console.error('获取商品库存详情失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取商品库存详情失败',
      error: error.message
    });
  }
};

/**
 * 更新商品库存信息
 */
exports.updateProductInventory = async (req, res) => {
  try {
    const { id } = req.params;
    const { minimumStock, maximumStock, stockUnit } = req.body;
    
    // 查询商品信息
    const product = await prisma.product.findUnique({
      where: { id: parseInt(id) }
    });
    
    if (!product) {
      return res.status(404).json({
        success: false,
        message: '商品不存在'
      });
    }
    
    // 更新商品库存信息
    const updatedProduct = await prisma.product.update({
      where: { id: parseInt(id) },
      data: {
        minimumStock: minimumStock !== undefined ? parseFloat(minimumStock) : product.minimumStock,
        maximumStock: maximumStock !== undefined ? parseFloat(maximumStock) : product.maximumStock,
        stockUnit: stockUnit || product.stockUnit,
        stockStatus: product.stockQuantity <= 0 ? 'out_of_stock' : 
                     (minimumStock !== undefined && product.stockQuantity <= parseFloat(minimumStock) ? 'warning' : 'normal')
      }
    });
    
    return res.status(200).json({
      success: true,
      data: updatedProduct,
      message: '商品库存信息更新成功'
    });
  } catch (error) {
    console.error('更新商品库存信息失败:', error);
    return res.status(500).json({
      success: false,
      message: '更新商品库存信息失败',
      error: error.message
    });
  }
}; 